package com.example.xwadmin.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.xw.common.annotation.Allow;
import com.example.xw.common.annotation.Login;
import com.example.xw.common.entity.Admin;
import com.example.xw.common.entity.User;
import com.example.xw.common.entity.Weibo;
import com.example.xw.common.service.AdminService;
import com.example.xw.common.vo.Result;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.UUID;

@RestController
public class AdminApi {
    @Resource(name = "myAdminServiceImpl")
    private AdminService adminService;

    @PostMapping("/api/register")
    @Login
    @Allow(role = 1,pms = "新增管理员")
    public ResponseEntity<Result<Admin>> register(@RequestBody Admin admin, HttpServletRequest request){
        Admin curAdmin = (Admin) request.getAttribute("cur_admin");
//        if (curAdmin==null)
//            return ResponseEntity.status(401).body(new Result<Admin>(4001,null,"请先登录"));
        if (curAdmin.getLevel()!=1){
            return ResponseEntity.status(401).body(new Result<Admin>(4001,null,"无权限"));
        }
        System.out.println(admin.getLoginName()+" "+admin.getLoginPwd());
        return ResponseEntity.ok(adminService.register(admin));
    }


    @PostMapping("/api/login")
    public ResponseEntity<Result<Admin>> login(String name, String pwd, HttpServletResponse response){
        Result<Admin> result = adminService.login(name,pwd);
        if(result.getCode()!=200){
            return ResponseEntity.status(401).body(result);
        }
        Admin admin=result.getData();
        //制造一个凭证，发送给浏览器，把它保存起来
        JwtBuilder builder= Jwts.builder();
        builder.setId(UUID.randomUUID().toString());
        builder.setIssuedAt(new Date());
        builder.setExpiration(new Date(System.currentTimeMillis()+20*60*1000));
        builder.signWith(SignatureAlgorithm.HS256,"111222");
        //携带的参数
        builder.claim("admin_id",admin.getId());
        builder.claim("admin_name",admin.getName());
        builder.claim("admin_loginname",admin.getLoginName());
        builder.claim("admin_level",admin.getLevel());
        builder.claim("admin_pmses",admin.getPmses());
        builder.setSubject(admin.getId()+"");
        String jwt=builder.compact();
        System.out.println(jwt);
        //在响应头中设置凭证
        response.setHeader("jwttoken",jwt);
        return ResponseEntity.ok(result);
    }



}

